package cn.iocoder.yudao.module.picturebook.service.audioself;


import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.bookcontext.BookContextDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.bookcontext.BookContextMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;


import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.picturebook.controller.admin.audioself.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.audioself.AudioSelfDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.audioself.AudioSelfMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 绘本自己录音 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AudioSelfServiceImpl implements AudioSelfService {

    @Resource
    private AudioSelfMapper audioSelfMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private BookContextMapper bookContextMapper;

    @Override
    public Integer createAudioSelf(AudioSelfSaveReqVO createReqVO, Long userId) {
        // 参数校验
        if (createReqVO == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (createReqVO.getBookId() == null) {
            throw new IllegalArgumentException("绘本ID不能为空");
        }
        if (createReqVO.getCurrentPage() == null || createReqVO.getCurrentPage().isEmpty()) {
            throw new IllegalArgumentException("当前页不能为空");
        }

        // 插入
        AudioSelfDO audioSelf = BeanUtils.toBean(createReqVO, AudioSelfDO.class);
        audioSelf.setCreator(String.valueOf(userId));
        //判断当前用户的的录音是否存在
        //如果为空值

        Integer audioId = audioSelfMapper.isExist(userId, createReqVO.getBookId(), createReqVO.getCurrentPage());
        if (audioId != null) {
            //更新录音
            audioSelf.setAudioId(audioId);
            audioSelfMapper.updateById(audioSelf);
            return audioId;
        }
        audioSelfMapper.insert(audioSelf);

        // 添加空值检查
        if (audioSelf.getAudioId() == null) {
            throw new RuntimeException("Failed to create audio self, audioId is null");
        }

        // 返回
        return audioSelf.getAudioId();
    }

    @Override
    public void updateAudioSelf(AudioSelfSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        if (updateReqVO.getAudioId() == null) {
            throw new IllegalArgumentException("音频ID不能为空");
        }

        // 校验存在
        validateAudioSelfExists(updateReqVO.getAudioId());
        // 更新
        AudioSelfDO updateObj = BeanUtils.toBean(updateReqVO, AudioSelfDO.class);
        audioSelfMapper.updateById(updateObj);
    }

    @Override
    public void deleteAudioSelf(Integer id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("音频ID不能为空");
        }

        // 校验存在
        validateAudioSelfExists(id);
        // 删除
        audioSelfMapper.deleteById(id);
    }

    @Override
    public void deleteAudioSelfListByIds(List<Integer> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("音频ID列表不能为空");
        }

        // 删除
        audioSelfMapper.deleteByIds(ids);
    }


    private void validateAudioSelfExists(Integer id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("音频ID不能为空");
        }

        if (audioSelfMapper.selectById(id) == null) {
            throw exception(AUDIO_SELF_NOT_EXISTS);
        }
    }

    @Override
    public AudioSelfDO getAudioSelf(Integer id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("音频ID不能为空");
        }

        return audioSelfMapper.selectById(id);
    }

    @Override
    public PageResult<AudioSelfRecordRespVO> getAudioSelfPage(AudioSelfPageReqVO pageReqVO, Long userId) {
        // 参数校验
        if (pageReqVO == null) {
            throw new IllegalArgumentException("分页请求参数不能为空");
        }
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        PageResult<AudioSelfDO> audioSelfDOPageResult = audioSelfMapper.selectPage(pageReqVO, userId);

        // 先根据存在的录音的中绘本id进行归类
        if (audioSelfDOPageResult.getList() == null) {
            return new PageResult<>(new ArrayList<>(), 0L);
        }

        Map<Long, List<AudioSelfDO>> bookIdMap = audioSelfDOPageResult.getList().stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(AudioSelfDO::getBookId));

        // 获取每个绘本的名字
        List<AudioSelfRecordRespVO> audioSelfRecordRespVOList = new ArrayList<>();

        for (Map.Entry<Long, List<AudioSelfDO>> entry : bookIdMap.entrySet()) {
            Long bookId = entry.getKey();
            List<AudioSelfDO> audioSelfDOList = entry.getValue();

            // 避免重复查询数据库
            BookDO bookDO = bookMapper.selectById(bookId);
            if (bookDO == null) continue; // 防止空指针

            AudioSelfRecordRespVO audioSelfRecordRespVO = new AudioSelfRecordRespVO();
            audioSelfRecordRespVO.setBookId(bookId);
            audioSelfRecordRespVO.setCoverUrl(bookDO.getCoverUrl());
            audioSelfRecordRespVO.setTitle(bookDO.getTitle());

            // 根据更新时间排序，获取最新的录音时间
            if (audioSelfDOList != null && !audioSelfDOList.isEmpty()) {
                audioSelfDOList.sort(Comparator.comparing(AudioSelfDO::getUpdateTime).reversed());
                if (!audioSelfDOList.isEmpty()) {
                    audioSelfRecordRespVO.setRecordTime(String.valueOf(audioSelfDOList.get(0).getUpdateTime()));
                }
            }

            // 获取内容并解析 JSON
            BookContextDO bookContextDO = bookContextMapper.selectById(bookId);
            if (bookContextDO != null && bookContextDO.getContext() != null) {
                String context = bookContextDO.getContext();
                try {
                    JSONObject contextJson = JSONObject.parseObject(context);
                    JSONArray mediaList = contextJson.getJSONArray("media_list");

                    if (mediaList != null) {
                        // 将用户录音按页码分组，便于快速查找
                        Map<String, AudioSelfDO> userAudioMap = audioSelfDOList.stream()
                                .filter(audio -> audio != null && audio.getCurrentPage() != null)
                                .collect(Collectors.toMap(AudioSelfDO::getCurrentPage, audio -> audio, (existing, replacement) -> existing));

                        // 遍历绘本的每一页，删除原音频并添加用户音频（如果有）
                        for (int j = 0; j < mediaList.size(); j++) {
                            JSONObject mediaItem = mediaList.getJSONObject(j);
                            if (mediaItem != null) {
                                String pageNum = mediaItem.getString("currentPage");

                                // 不管用户有没有音频，都删除原本的
                                mediaItem.remove("audio_url");

                                // 如果用户有该页的录音，则添加
                                if (pageNum != null && userAudioMap.containsKey(pageNum)) {
                                    AudioSelfDO userAudio = userAudioMap.get(pageNum);
                                    mediaItem.put("audio_url", userAudio.getAudioIdUrl());
                                }
                            }
                        }

                        // 更新处理后的内容
                        audioSelfRecordRespVO.setBookContent(contextJson.toJSONString());
                    }
                } catch (Exception e) {
                    // JSON解析异常处理
                    audioSelfRecordRespVO.setBookContent("{}");
                }
            }

            audioSelfRecordRespVOList.add(audioSelfRecordRespVO);
        }

        // 返回分页结果
        return new PageResult<>(audioSelfRecordRespVOList, audioSelfDOPageResult.getTotal());
    }

}